package org.huawei260.basic.part_3_tree.Heap;

/**
 * @Author: qingle
 * @Date: 2024/11/29-18:47
 * @Description:
 * @Version: 1.0
 */
import java.io.*;
import java.util.*;

public class MergeSorter {
	public static void main(String[] args) throws IOException {
		File[] tempFiles = new File("temp").listFiles((dir, name) -> name.startsWith("temp") && name.endsWith(".txt"));
		if (tempFiles == null || tempFiles.length == 0) {
			System.out.println("No temp files found.");
			return;
		}

		try (BufferedWriter writer = new BufferedWriter(new FileWriter("sorted_ids.txt"))) {
			PriorityQueue<File> filePriorityQueue = new PriorityQueue<>(Comparator.comparingInt(a -> Integer.parseInt(a.getName().split("temp")[1].split("\\.")[0])));
			for (File file : tempFiles) {
				try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
					filePriorityQueue.add(file);
				}
			}

			while (!filePriorityQueue.isEmpty()) {
				File currentFile = filePriorityQueue.poll();
				try (BufferedReader reader = new BufferedReader(new FileReader(currentFile))) {
					String line;
					while ((line = reader.readLine()) != null) {
						writer.write(line);
						writer.newLine();
					}
				}
				// 删除已处理的临时文件
				if (!currentFile.delete()) {
					System.out.println("Failed to delete file: " + currentFile.getName());
				}
			}
		}
		System.out.println("Merging completed successfully.");
	}
}